package com.ruoyi.common.sms.utils;

import com.aliyun.teaopenapi.models.Config;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.utils.uuid.IdUtils;
import com.ruoyi.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.TimeUnit;

import static com.aliyun.teautil.Common.toJSONString;


@Component
public class SendSMS {
    @Autowired
    private RedisService redisService;

    public String send() throws Exception {
        // 初始化请求客户端
//        Config config = new Config()
//                // 配置 AccessKey ID，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
//                .setAccessKeyId("LTAI5t9fBwG6HdT1VDdzX9cp")
//                // 配置 AccessKey Secret，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
//                .setAccessKeySecret("XWb86dc7YSPzDN2Kcf49n44lwIGzvC");
//        Client client = new Client(config);
//        // 配置 Endpoint
//        config.endpoint = "dysmsapi.aliyuncs.com";
//
//        // 构造请求对象，请填入请求参数值
//        String code = getCode();
//        SendSmsRequest sendSmsRequest = new SendSmsRequest()
//                .setPhoneNumbers("15890088758")
//                .setSignName("阿里云短信测试")
//                .setTemplateCode("SMS_154950909")
//                .setTemplateParam("{\"code\":\"" + code + "\"}");
//
//        // 获取响应对象
//        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
//        System.out.println("{\"code\": \"" +code + "\"}");
//        System.out.println(toJSONString(sendSmsResponse));

        // 写入redis
        String code = "6666"; // 暂时使用 后续删除
        String uuid = IdUtils.randomUUID();
        redisService.setCacheObject(uuid, code, CacheConstants.VERIFY_CODE, TimeUnit.MINUTES);
        return uuid;
    }

    public static String getCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }
}
